package com.wkq.util

import net.lingala.zip4j.ZipFile
import net.lingala.zip4j.exception.ZipException
import net.lingala.zip4j.model.ZipParameters
import net.lingala.zip4j.model.enums.EncryptionMethod
import java.io.File

/**
 *
 *@Author: wkq
 *
 *@Time: 2025/7/12 15:48
 *
 *@Desc: 基于 zip4j 解压工具类
 */


object FileZipUtil {

    interface Callback {
        fun onSuccess(message: String)
        fun onError(error: Throwable)
    }

    /**
     * 压缩文件或文件夹（可加密）
     * @param files 要压缩的文件或目录列表
     * @param outputZipPath 输出的ZIP路径
     * @param password 可选密码（为空则不加密）
     * @param callback 结果回调
     */
    fun compress(
        files: List<File>,
        outputZipPath: String,
        password: String? = null,
        callback: Callback?
    ) {
        try {
            val zipFile = if (!password.isNullOrEmpty()) {
                ZipFile(outputZipPath, password.toCharArray())
            } else {
                ZipFile(outputZipPath)
            }

            val parameters = ZipParameters().apply {
                if (!password.isNullOrEmpty()) {
                    isEncryptFiles = true
                    encryptionMethod = EncryptionMethod.AES
                }
            }

            zipFile.addFiles(files, parameters)
            callback?.onSuccess("压缩成功: $outputZipPath")

        } catch (e: Exception) {
            callback?.onError(e)
        }
    }

    /**
     * 解压ZIP文件（支持加密ZIP）
     * @param zipFilePath ZIP文件路径
     * @param destination 解压到的目录
     * @param password 可选密码（若压缩包加密）
     * @param callback 结果回调
     */
    fun decompress(
        zipFilePath: String,
        destination: String,
        password: String? = null,
        callback: Callback?
    ) {
        try {
            val zipFile = ZipFile(zipFilePath)

            if (zipFile.isEncrypted) {
                if (password.isNullOrEmpty()) {
                    throw ZipException("该压缩包已加密，请提供密码")
                }
                zipFile.setPassword(password.toCharArray())
            }

            zipFile.extractAll(destination)
            callback?.onSuccess(destination)

        } catch (e: Exception) {
            callback?.onError(e)
        }
    }
}
